<?php

//require_once "../users/Users.php";

class Database {
	private $mysqli = NULL;
	
	public function Prepare($sql) {
		$stmt = $this->mysqli->prepare($sql);
		return $stmt;
	}
   
	public function Connect(DBConfig $config) {
		$this->mysqli = new mysqli(
							$config->host,
							$config->user,
							$config->password,
							$config->db
						);
	   
		if ($this->mysqli->connect_error) {
			throw new Exception($this->mysqli->connect_error);
		}
	   
		$this->mysqli->set_charset("utf8");
	   
		return true;
	}
	
	public function GetManyBindToObjects($stmt, $class) {
	   
		if ($stmt->execute() == FALSE) {
			throw new Exception($this->mysqli->error);
		}
		
		$objects = array();
		
		$result = $stmt->get_result();
		
		while ($obj = $result->fetch_object($class)) {
	    	$objects[] = $obj;
	    }
		
		return $objects;		
	}
	
	public function ExecuteNonQuery($stmt) {
		if ($stmt->execute() == FALSE) {
			throw new Exception($this->mysqli->error);
		}
	}
   
	public function SelectOne($stmt) {
		if ($stmt->execute() == FALSE) {
			throw new Exception($this->mysqli->error);
		}

		$stmt->bind_result($ret);
	   
		$stmt->fetch();
	   
		$stmt->close();
	   	   
		return $ret;
	}
   
	public function Close() {
		return $this->mysqli->close();
	}

	public static function test(DBConfig $dbConfig) {
		$db = new Database();
	   
		if ($db->Connect($dbConfig) == false) {
			echo "Database Connect failed";
			return false;
		}
	   
		if ($db->SelectOne("SELECT COUNT(*) FROM NotEmpty") != 2) {
			echo "Database SelectOne failed";
			return false;
		}
	   
		if ($db->Close() == false) {
			echo "Database Close failed";
			return false;
		}
		
		return true;
	}      
}
